package com.keyinong.caizhengting.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.tools.SystemBarTintManager;
import com.keyinong.caizhengting.activity.DingdandetailActivity;
import com.keyinong.caizhengting.adapter.MyteamorderAdapter;
import com.keyinong.caizhengting.entity.MyorderEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的订单fragment(new)
 */

public class MyorderFragment extends Fragment {

    /**
     * 获得数据
     */
    List<MyorderEntity> infolist;
    //	String teamorderid;
    HttpTools httptools = null;
    String token = "";
    int offset = 0;
    int page = 8;
    String fee;
    double allprice;

    private MyteamorderAdapter myteamorderAdapter;
    /**
     * 上下拉刷新
     */
    private PullToRefreshListView pull_myorder;
    /**
     * 份数
     */
    private int shuliang;
    /**
     * 总价
     */
    private double zongjia;
    /**
     * 无订单信息状态
     */
    private TextView tv_state;
    private RelativeLayout rl_none;

    private int mType = 0;
    private TextView mTvCanteen;
    private TextView mTvMarket;
    private ImageView mIvCanteen;
    private ImageView mIvMarket;
    private ConstraintLayout mClCanteen;
    private ConstraintLayout mClMarket;

    /**
     * item点击事件
     */
    private OnItemClickListener itemclicke = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position,
                                long id) {
            Intent intent = new Intent(getActivity(), DingdandetailActivity.class);
            intent.putExtra("orderid", infolist.get(position - 1).getId());
            intent.putExtra("type", mType);
            startActivity(intent);
        }
    };
    /**
     * 上下拉刷新
     */
    private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {

        @Override
        public void onPullDownToRefresh(
                PullToRefreshBase<ListView> refreshView) {
            offset = 0;
            infolist.clear();
            //				shuliang=0;
            httptools.myorder(token, page + "", offset + "", mType, new JsonDingdan());
            if (!NetWorkUtil.isNetwork(getActivity())) {
                Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_myorder.onRefreshComplete();
            }
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            offset += page;
            //				shuliang=0;
            httptools.myorder(token, page + "", offset + "", mType, new JsonDingdan());
            if (!NetWorkUtil.isNetwork(getActivity())) {
                pull_myorder.onRefreshComplete();
            }
        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        return inflater.inflate(R.layout.personalorder, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        SystemBarTintManager tintManager = new SystemBarTintManager(getActivity());
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(getResources().getColor(R.color.white_1));
        super.onActivityCreated(savedInstanceState);
        initRes();
    }

    private void initRes() {
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");

        mTvCanteen = (TextView) getView().findViewById(R.id.tv_canteen);
        mTvMarket = (TextView) getView().findViewById(R.id.tv_market);

        mIvCanteen = (ImageView) getView().findViewById(R.id.iv_canteen);
        mIvMarket = (ImageView) getView().findViewById(R.id.iv_market);

        mClCanteen = (ConstraintLayout) getView().findViewById(R.id.cl_canteen);
        mClMarket = (ConstraintLayout) getView().findViewById(R.id.cl_market);

        mClCanteen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvCanteen.setTextColor(Color.parseColor("#F63333"));
                mTvMarket.setTextColor(Color.parseColor("#999999"));
                mIvCanteen.setVisibility(View.VISIBLE);
                mIvMarket.setVisibility(View.INVISIBLE);
                mType = 0;
                Dingdan();
                //if (null != myteamorderAdapter) {
                //    myteamorderAdapter.notifyDataSetChanged();
                //}
                //myteamorderAdapter.notifyDataSetChanged();

            }
        });

        mClMarket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvCanteen.setTextColor(Color.parseColor("#999999"));
                mTvMarket.setTextColor(Color.parseColor("#F63333"));
                mIvCanteen.setVisibility(View.INVISIBLE);
                mIvMarket.setVisibility(View.VISIBLE);
                mType = 14;
                Dingdan();
                //if (null != myteamorderAdapter) {
                //    myteamorderAdapter.notifyDataSetChanged();
                //}

            }
        });

        pull_myorder = (PullToRefreshListView) getView().findViewById(R.id.pull_wodedingdan);
        pull_myorder.setMode(Mode.BOTH);
        pull_myorder.setOnRefreshListener(onrefresh);
        pull_myorder.setOnItemClickListener(itemclicke);
        tv_state = (TextView) getView().findViewById(R.id.tv_state);
        rl_none = (RelativeLayout) getView().findViewById(R.id.rl_none);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dingdan();
    }

    /**
     * 订单列表
     */
    private void Dingdan() {
        if (!NetWorkUtil.isNetwork(getActivity())) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        infolist = new ArrayList<>();

        if (httptools == null) {
            httptools = new HttpTools(getActivity());
        }
        httptools.myorder(token, "" + page, "" + offset, mType, new JsonDingdan());
    }

    public class JsonDingdan extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(getActivity(), "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.w("WZY", response.toString());
            MyShowDialog.closeLoadingDialog();
            initRes();
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    JSONArray array = response.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        String id = data.getString("id");
                        String order_time = data.getString("order_time");
                        String state = data.getString("state");
                        String total = data.getString("total");
                        JSONArray array2 = data.getJSONArray("details");
                        if (array2.length() != 0) {
                            JSONObject details = array2.getJSONObject(0);
                            String name = details.getString("name");
                            String amount = details.getString("amount");
                            String price = details.getString("price");
                            for (int j = 0; j < array2.length(); j++) {
                                JSONObject detail = array2.getJSONObject(j);
                                String fenshu = detail.getString("amount");
                                String jiage = detail.getString("price");
                                zongjia += Integer.parseInt(fenshu) * Double.parseDouble(jiage);
                                shuliang += Integer.parseInt(fenshu);
                            }
                            int count = array2.length();
                            infolist.add(new MyorderEntity(id, state, name, amount, price, order_time, "" + shuliang, total, "", "", count, "" + allprice, ""));
                            zongjia = 0.0;
                            shuliang = 0;
                        }
                    }

                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
                if (infolist.size() == 0) {
                    tv_state.setText("暂无订单信息");
                    rl_none.setVisibility(View.VISIBLE);
                    pull_myorder.setVisibility(View.GONE);
                } else {
                    rl_none.setVisibility(View.GONE);
                    pull_myorder.setVisibility(View.VISIBLE);
                    myteamorderAdapter = new MyteamorderAdapter(getActivity(), infolist, mType);
                    pull_myorder.setAdapter(myteamorderAdapter);
                    pull_myorder.getRefreshableView().setSelection(offset);
                    pull_myorder.setDividerDrawable(null);
                    myteamorderAdapter.notifyDataSetChanged();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                pull_myorder.onRefreshComplete();
            }
        }
    }

}
